package start.spring.basic.log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
import start.spring.basic.dynamic.DynamicKafkaDAO;
import start.spring.basic.util.common.StringUtil;

/**
 * 
 * ****************************************************************************
 * service层日志通过kafka保存到数据库
 *
 * @author(作者)：xuyongyun	
 * @date(创建日期)：2023年2月24日
 ******************************************************************************
 */
@Slf4j
@Component
public class ServiceDetails {
	
	@Autowired
	DynamicKafkaDAO kafkaDAO;

	/**
	 * 发送日志详情到kafka
	 *	
	 * @param sysType 日志所属子系统代码
	 * @param bizType 日志所属业务类型
	 * @param userId 操作人id
	 * @param userName 操作人名称
	 * @param details 日志详情，根据实际业务生成的可序列化对象
	 * @since           1.0
	 */
	public void saveDetails(String sysType,String bizType,String userId,String userName,Object... details) {
		JSONObject appLog = new JSONObject();
		appLog.put("systemType", sysType);
		appLog.put("businessType", bizType);
		
		String traceId = MDC.get(LogConstant.REQUEST_KEY_TRACEID);
		if(StringUtil.isEmpty(traceId)) {
			appLog.put("traceId", "");
		}else{
			appLog.put("traceId", traceId);
		}
		
		if(StringUtil.isEmpty(userId)) {
			appLog.put("userId", "");
		}else {
			appLog.put("userId", userId);
		}
		
		if(StringUtil.isEmpty(userName)) {
			appLog.put("userName", "");
		}else {
			appLog.put("userName", userName);
		}
		
		List<Object> detailList = new ArrayList<>();
		if(details==null||details.length==0) {
			detailList.add("");
		}else {
			detailList.addAll(Arrays.asList(details));
		}
		appLog.put("operDetail", detailList);
		
		appLog.put("ip", "");
		appLog.put("className", "");
		appLog.put("methodName", "");
		appLog.put("requestArgs", "");
		appLog.put("url", "");
		appLog.put("startTime", "");
		appLog.put("code", "");
		appLog.put("msg", "");
		appLog.put("endTime", "");
		appLog.put("clhs", "");
		appLog.put("operResult", "");
		
		log.info("operate detail: {}", appLog);
		
		if(kafkaDAO.kafkaExsit(LogConstant.KAFKA_KEY_LOGS)) {
			kafkaDAO.send(LogConstant.KAFKA_KEY_LOGS, LogConstant.LOGS_TOPIC, appLog.toJSONString());
		}
	}
}
